package com.wehealth;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.Dr_List;
import com.wehealth.Dr_Free;
import com.wehealth.adapter.Adapter_Health_search_food_item;
import com.wehealth.adapter.Adapter_Health_search_item;
import com.wehealth.adapter.Adapter_QuestionList;
import com.wehealth.dm.DM_HealthSearchFoodAndSportClassify;
import com.wehealth.dm.DM_HealthSearchFoodInfo;
import com.wehealth.dm.DM_HealthSearchList;
import com.wehealth.dm.DM_HealthSearchSportInfo;
import com.wehealth.dm.QuestionData;
import com.wehealth.util.GetUrl;

@SuppressLint("ValidFragment")
public class Health_search_sport_descrip extends Fragment {
	
	private MainActivity context;


	private static  String JSONResult;
	private static final int NET_ERROR = -100;
	private DM_HealthSearchList  mFood;
	private DM_HealthSearchSportInfo mSportInfo;

	
	private TextView  nameTv;
	private TextView  energyTv;
	private TextView  levelTv;
	private TextView  suitTV;
	private TextView  timeTv;
	private TextView descript_sport;
	
	private TextView mSportRecordTx;
	
	private View mSportInfoView;
	private View mSportRecordView;
	private boolean mDisplaySportInfo = true;
	
	private static final int FOOD_ZAO = 0;
	private static final int FOOD_ZHONG =1;
	private static final int FOOD_WAN =2;
	private static final int FOOD_JIACAN =3;
	private List<TextView>  foodTime;
	private int mFoodTime =0;

	public  Health_search_sport_descrip( )
	{
	
	}
	
	public Health_search_sport_descrip(DM_HealthSearchList  mFoodDescrip){
		mFood = mFoodDescrip;
	}

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.health_search_sport_descrip, null);
	}
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		
		MainActivity activity = (MainActivity)getActivity();
		context = activity;
		mSportInfo = new DM_HealthSearchSportInfo();
		foodTime = new ArrayList<TextView>();
		
		nameTv = (TextView)context.findViewById(R.id.sport_name);
		energyTv = (TextView)context.findViewById(R.id.sport_energy);
		levelTv = (TextView)context.findViewById(R.id.sport_level_tv);
		timeTv = (TextView)context.findViewById(R.id.sport_time);
		descript_sport = (TextView)context.findViewById(R.id.sport_instruct);
		
		ConnService();
		
		MobclickAgent.openActivityDurationTrack(false);
		Button bBack = (Button) activity.findViewById(R.id.b_back);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					if(mDisplaySportInfo){
                    MainActivity activity = (MainActivity) getActivity();                       
                    activity.switchContentHome();
					}else{
		                mSportInfoView.setVisibility(View.VISIBLE);
		                mSportRecordView.setVisibility(View.GONE);
		                String ok = getString(R.string.health_search_food_descript_record);
		                mSportRecordTx.setText(ok);
		                mDisplaySportInfo = true;
					}
				}
			});
		 
		 
		 mSportInfoView =(View)context.findViewById(R.id.sport_descript);
		 mSportRecordView=(View)context.findViewById(R.id.sport_record);
		 mSportRecordTx =(TextView)context.findViewById(R.id.health_search_sport_descrip_record);
		 mSportRecordTx.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mSportInfoView.setVisibility(View.GONE);
                mSportRecordView.setVisibility(View.VISIBLE);
                String ok = getString(R.string.health_search_food_descript_ok);
                mSportRecordTx.setText(ok);
                mDisplaySportInfo = false;
            }
        });
		 
		 
		 TextView food_zao =(TextView)context.findViewById(R.id.food_zao);
		 food_zao.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                setFoodTime(FOOD_ZAO);
                
            }
        });
		 foodTime.add(food_zao);
		 
	      TextView food_zhong =(TextView)context.findViewById(R.id.food_zhong);
	      food_zhong.setOnClickListener(new OnClickListener() {
	            
	            @Override
	            public void onClick(View arg0) {
	                // TODO Auto-generated method stub
	                setFoodTime(FOOD_ZHONG);
	            }
	        });
	         foodTime.add(food_zhong);
	         
	         
	         TextView food_wan =(TextView)context.findViewById(R.id.food_wan);
	         food_wan.setOnClickListener(new OnClickListener() {
	            
	            @Override
	            public void onClick(View arg0) {
	                // TODO Auto-generated method stub
	                setFoodTime(FOOD_WAN);
	            }
	        });
	         foodTime.add(food_wan);
	         
	      TextView food_jiacan =(TextView)context.findViewById(R.id.food_jiacan);
	      food_jiacan.setOnClickListener(new OnClickListener() {
	            
	            @Override
	            public void onClick(View arg0) {
	                // TODO Auto-generated method stub
	                setFoodTime(FOOD_JIACAN);
	            }
	        });
	         foodTime.add(food_jiacan);
		 
		 
		 
	}
	
	
	private void setFoodTime(int index){
	    int blueColor = context.getResources().getColor(R.color.text_color_blue_3);
	    int whiteColor = context.getResources().getColor(R.color.white);
	    foodTime.get(mFoodTime).setTextColor(blueColor);
	    foodTime.get(index).setTextColor(whiteColor);
	   switch (mFoodTime) {
        case 0:
            foodTime.get(mFoodTime).setBackgroundResource(R.drawable.bg_blue_rectangle_left_padding);
            break;
        case 1:
        case 2:
            foodTime.get(mFoodTime).setBackgroundResource(R.drawable.bg_blue_rectangle);
            break;
        case 3:
            foodTime.get(mFoodTime).setBackgroundResource(R.drawable.bg_blue_rectangle_right_padding);
            break;
        default:
            break;
	   }
	   
    switch (index) {
       case 0:
           foodTime.get(index).setBackgroundResource(R.drawable.bg_blue_rectangle_left_solid);
           break;
       case 1:
       case 2:
           foodTime.get(index).setBackgroundResource(R.drawable.bg_blue_rectangle_solid);
           break;
       case 3:
           foodTime.get(index).setBackgroundResource(R.drawable.bg_blue_rectangle_right_solid);
           break;
       default:
           break;
      }
	    
    mFoodTime = index;
	}

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("Health_search_food_descrip"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("Health_search_food_descrip"); 
    }
	

    private void  ConnService(){
        
        //读取接口数据
        new Thread(){
            @Override
            public void run(){
            //你要执行的方法
                try {
                    InitThisView();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            //执行完毕后给handler发送一个空消息
            handler.sendEmptyMessage(0);
            }
            }.start();
    }
    
    private void  InitThisView() throws IOException
    {
         String urlAPI = GetUrl.GetHealthSearch_SportInfo_Url();
         HttpPost httpRequest= new HttpPost(urlAPI);
         List <NameValuePair> params = new ArrayList <NameValuePair>();

         params.add(new BasicNameValuePair("ID",mFood.getID()));
         try
         {
             httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
             HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);       
             if(httpResponse.getStatusLine().getStatusCode() == 200)
             {  
                 JSONResult = EntityUtils.toString(httpResponse.getEntity()); 
             }       
         }
         catch(Exception e)
         {      
            
         }

    }
    
    
    
    //定义Handler对象
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg){
        super.handleMessage(msg);
        //处理UI
        if(JSONResult ==null){
            openDialog(NET_ERROR);
        }else{
            BindList(JSONResult);
            JSONResult =null;
        }
        }
    };
    

    
    //将JSON数据绑定到LISTVIEW
    private void BindList(String strJSON){
       try{
                JSONObject jsonObject = new JSONObject(strJSON); 
                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
                for(int i=0; i<aNews.length(); i++)
                    {
                	mSportInfo.setName(aNews.getJSONObject(i).getString("name"));
                	mSportInfo.setEnergy(aNews.getJSONObject(i).getString("energy"));
                	mSportInfo.settime(aNews.getJSONObject(i).getString("time"));
                	String  level =aNews.getJSONObject(i).getString("level");
                	mSportInfo.setlevel(level);
                	String  suit =aNews.getJSONObject(i).getString("suit");
                	mSportInfo.setsuit(suit);
                  String descript = aNews.getJSONObject(i).getString("description");
                  mSportInfo.setDescription(descript);
                }
                updateViewData(mSportInfo);
            }
            catch(JSONException ex)
            {
                    Log.e("JSON Error: ", ex.toString()); 
            }
    }
    
    
    private  void updateViewData(DM_HealthSearchSportInfo data){
		nameTv.setText(data.getName());
		String energyValue = data.getEnergy()+getString(R.string.health_search_sport_descript_energy);
		energyTv.setText(energyValue);
		levelTv.setText(data.getlevel());
		String time = data.gettime()+getString(R.string.health_search_sport_descript_time);
		timeTv.setText(time);
		descript_sport.setText(data.getDescription());
    	
    }
    
    
    
    private void openDialog(final int result){
        context.openDialogBt(result);
     }  
    

}
